/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.myapp.beans;

import com.myapp.entities.User;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.traversal.DocumentTraversal;
import org.w3c.dom.traversal.NodeFilter;
import org.w3c.dom.traversal.NodeIterator;

/**
 *
 * @author Vinh_Dragon
 */
public class Helper {
    /**
     *getListUser
     * @param realPath
     * @return
     */
    public ArrayList<User> getListUser(String realPath) {
        try {

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            DocumentBuilder builder = factory.newDocumentBuilder();

            //realPath = getServlet().getServletContext().getRealPath("/");
            String path = realPath + "user.xml";
            Document doc = builder.parse(new File(path));

            return returnNodes(doc);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 
     * @param doc
     * @return
     */
    public ArrayList<User> returnNodes(Document doc) {
        try{
        ArrayList<User> lst = new ArrayList<User>();
        DocumentTraversal docTraversal = (DocumentTraversal) doc;
        NodeIterator nodeIterator = docTraversal.createNodeIterator(doc.getDocumentElement(), NodeFilter.SHOW_ELEMENT, null, true);
        Node currentNode;
        while ((currentNode=nodeIterator.nextNode()) != null) {

                if (currentNode.getNodeName().equals("user")) {
                    NodeList child = currentNode.getChildNodes();
                    User user = null;
                    for (int j = 0; j < child.getLength(); j++) {
                        Element userNode = (Element) child.item(j).getParentNode();
                        user = new User();
                        user.setId(userNode.getAttribute("id"));
                        user.setUsername(userNode.getElementsByTagName("username").item(0).getTextContent());
                        user.setPassword(userNode.getElementsByTagName("password").item(0).getTextContent());
                        user.setRole(userNode.getElementsByTagName("role").item(0).getTextContent());
       
                        lst.add(user);
                    }
                }

                //currentNode = nodeIterator.nextNode();
            }

            return lst;
        } catch (Exception ex) {
            Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     * 
     * @param doc
     * @param id
     * @param question
     * @param answer
     */
    public void createElement(Document doc, String id, String question, ArrayList<String> answer, String filePath) {
        try {
            Element elemQuestion = doc.createElement("question");
            elemQuestion.setAttribute("id", id);
            elemQuestion.setAttribute("status", "show");

            Element elemContent = doc.createElement("question-content");
            elemContent.setTextContent(question);

            elemQuestion.appendChild(elemContent);
            for (int i = 0; i < answer.size(); i++) {
                Element elemAns = doc.createElement("answer");
                elemAns.setAttribute("id", String.valueOf(i+1));
                elemAns.setTextContent(answer.get(i).toString());

                elemAns.setAttribute("statistic", "0");
                elemAns.setTextContent(answer.get(i).toString());
                
                elemQuestion.appendChild(elemAns);
            }

            doc.getDocumentElement().appendChild(elemQuestion);

            File file = new File(filePath);

            FileOutputStream fos = new FileOutputStream(file);

            outputData(doc, fos);

            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param doc
     * @param output
     * @throws Exception
     */
    public void outputData(Document doc, OutputStream output) throws Exception {
        try {
            OutputFormat format = new OutputFormat();
            format.setIndenting(true);

            XMLSerializer xs = new XMLSerializer(output, format);

            xs.serialize(doc);

            output.flush();
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 
     * @param path
     * @return
     */
    public Document getDocument(String path) {
        try {

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

            DocumentBuilder builder = factory.newDocumentBuilder();

            //realPath = getServlet().getServletContext().getRealPath("/");
            Document doc = builder.parse(new File(path));

            return doc;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     *
     * @return
     * @throws Exception
     */
    public Document createDocument(String rt) throws Exception {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.newDocument();

            Element root = doc.createElement(rt);
            doc.appendChild(root);

            return doc;
        } catch (Exception ex) {
            throw ex;
        }
    }
    /**
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    public Document createDocument(String fileName, String rt) throws Exception {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(fileName);

            Element root = doc.getDocumentElement();
            if (!root.getTagName().equals(rt)) {
                throw new Exception("Xml file is invalid format");
            }

            return doc;
        } catch (Exception ex) {
            throw ex;
        }
    }

    public void createSurveyElement(Document doc, String id, String question, ArrayList<String> answer, String filePath) {
        try {
            Element elemQuestion = doc.createElement("question");
            elemQuestion.setAttribute("id", id);

            //elemQuestion.setAttribute("status", "show");
            
            Element elemContent = doc.createElement("question-content");
            elemContent.setTextContent(question);

            elemQuestion.appendChild(elemContent);
            for (int i = 0; i < answer.size(); i++) {
                Element elemAns = doc.createElement("answer");
                elemAns.setAttribute("id", String.valueOf(i+1));
                elemAns.setTextContent(answer.get(i).toString());

                elemAns.setAttribute("statistic", "0");
                elemAns.setTextContent(answer.get(i).toString());

                elemQuestion.appendChild(elemAns);
            }

            doc.getDocumentElement().appendChild(elemQuestion);

            File file = new File(filePath);

            FileOutputStream fos = new FileOutputStream(file);

            outputData(doc, fos);

            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
